package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.mapper.OrderInfoMapper;
import com.zhentao.mapper.OrderItemMapper;
import com.zhentao.mapper.ProductMapper;
import com.zhentao.pojo.OrderInfo;
import com.zhentao.pojo.OrderItem;
import com.zhentao.pojo.Product;
import com.zhentao.service.OrderService;
import com.zhentao.vo.OrderCreateVO;
import com.zhentao.vo.OrderDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderInfoMapper orderInfoMapper;
    private final OrderItemMapper orderItemMapper;
    private final ProductMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(OrderCreateVO orderCreateVO) {
        // 1. 校验商品
        List<Long> productIds = orderCreateVO.getProductIds();
        List<Integer> counts = orderCreateVO.getCounts();
        if (productIds.size() != counts.size()) {
            throw new RuntimeException("商品数据异常");
        }

        // 2. 创建订单
        String orderNo = UUID.randomUUID().toString().replace("-", "");
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(orderCreateVO.getUid());
        orderInfo.setOrderNo(orderNo);
        orderInfo.setTotalAmount(orderCreateVO.getTotalAmount());
        orderInfo.setPayAmount(orderCreateVO.getPayAmount() != null ? orderCreateVO.getPayAmount() : orderCreateVO.getTotalAmount());
        orderInfo.setPayType(orderCreateVO.getPayType());
        orderInfo.setStatus(0); // 待支付
        orderInfo.setCreateTime(new Date());
        orderInfo.setUpdateTime(new Date());
        orderInfo.setIsDeleted(1);
        orderInfoMapper.insert(orderInfo);

        // 3. 创建订单项并更新库存
        for (int i = 0; i < productIds.size(); i++) {
            Long productId = productIds.get(i);
            Integer count = counts.get(i);

            // 获取商品信息
            List<Product> products = productMapper.selectList(new LambdaQueryWrapper<Product>().eq(Product::getId, productId));
               for (Product product: products){
                if (product == null || product.getIsDeleted() == 0 || product.getStatus() == 0) {
                    throw new RuntimeException("商品不存在或已下架");
                }
                if (product.getStock() < count) {
                    throw new RuntimeException("商品库存不足");
                }

                   // 创建订单项
                   OrderItem orderItem = new OrderItem();
                   orderItem.setOrderId(orderInfo.getId());
                   orderItem.setProductId(productId);
                   orderItem.setCount(count);
                   orderItem.setPrice(BigDecimal.valueOf(product.getPrice())); // 转换为BigDecimal
                   orderItem.setCreateTime(new Date());
                   orderItem.setUpdateTime(new Date());
                   orderItem.setIsDeleted(1);
                   orderItemMapper.insert(orderItem);

                   // 更新库存和销量
                   product.setStock(product.getStock() - count);
                   product.setSaleNum(product.getSaleNum() + count);
                   productMapper.updateById(product);
            }
        }

        return orderNo;
    }

    @Override
    public OrderDetailVO getOrderDetail(Long userId, String orderNo) {
        // 1. 查询订单信息
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId, userId)
                .eq(OrderInfo::getOrderNo, orderNo)
                .eq(OrderInfo::getIsDeleted, 1);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
        if (orderInfo == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 转换为VO
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        BeanUtils.copyProperties(orderInfo, orderDetailVO);
        return orderDetailVO;
    }

    @Override
    public List<OrderDetailVO> getMyOrders(Long userId) {
        // 查询用户的所有订单
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId, userId)
                .eq(OrderInfo::getIsDeleted, 1)
                .orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);;
        // 转换为VO
        List<OrderDetailVO> orderDetailVOs = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            System.err.println(orderInfo);
            OrderDetailVO orderDetailVO = new OrderDetailVO();
            BeanUtils.copyProperties(orderInfo, orderDetailVO);
            orderDetailVOs.add(orderDetailVO);
        }
        return orderDetailVOs;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long userId, String orderNo) {
        // 1. 查询订单
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId, userId)
                .eq(OrderInfo::getOrderNo, orderNo)
                .eq(OrderInfo::getIsDeleted, 1);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
        if (orderInfo == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 检查订单状态
        if (orderInfo.getStatus() != 0) {
            throw new RuntimeException("订单状态不允许取消");
        }

        // 3. 修改订单状态
        orderInfo.setStatus(4); // 已取消
        orderInfo.setUpdateTime(new Date());
        orderInfoMapper.updateById(orderInfo);

        // 4. 恢复商品库存
        LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(OrderItem::getOrderId, orderInfo.getId())
                .eq(OrderItem::getIsDeleted, 1);
        List<OrderItem> orderItems = orderItemMapper.selectList(itemWrapper);

        for (OrderItem orderItem : orderItems) {
            Product product = productMapper.selectById(orderItem.getProductId());
            if (product != null) {
                product.setStock(product.getStock() + orderItem.getCount());
                product.setSaleNum(product.getSaleNum() - orderItem.getCount());
                productMapper.updateById(product);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String payOrder(Long userId, String orderNo) {
        // 1. 查询订单
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId, userId)
                .eq(OrderInfo::getOrderNo, orderNo)
                .eq(OrderInfo::getIsDeleted, 1);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
        if (orderInfo == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 检查订单状态
        if (orderInfo.getStatus() != 0) {
            throw new RuntimeException("订单状态不正确");
        }

        // 3. 调用支付接口（这里模拟返回支付URL）
        // TODO: 实际项目中需要对接真实的支付系统
        String payUrl = "http://payment.example.com/pay/" + orderNo;

        // 4. 更新订单状态
        orderInfo.setStatus(1); // 待发货
        orderInfo.setUpdateTime(new Date());
        orderInfoMapper.updateById(orderInfo);

        return payUrl;
    }
}
